package mat;


import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecutorUtils
{
	public static ExecutorService createPool(String poolName, int maxThreads)
	{
		ExecutorService executorService = new ThreadPoolExecutor(maxThreads, maxThreads,
	                0l, TimeUnit.MILLISECONDS,
	                new LinkedBlockingQueue<Runnable>(),
	                new DaemonThreadFactory(poolName));			
	        return executorService;
	}
	public static void getAllAndRemove(List<Future<?>> futures)
	{
		Iterator<Future<?>> it = futures.iterator();
		while (it.hasNext())
		{
			Future<?> fut = it.next();
			it.remove();
			
			try
			{
				fut.get();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	static class DaemonThreadFactory implements ThreadFactory 
	{
	    static final AtomicInteger poolNumber = new AtomicInteger(1);
	    final ThreadGroup group;
	    final AtomicInteger threadNumber = new AtomicInteger(1);
	    final String namePrefix;

	    DaemonThreadFactory(String poolName) 
	    {
	        SecurityManager s = System.getSecurityManager();
	        group = (s != null)? s.getThreadGroup() :
	                             Thread.currentThread().getThreadGroup();
	        namePrefix = poolName + "-" +
	                      poolNumber.getAndIncrement() +
	                     "-thread-";
	    }

	    public Thread newThread(Runnable r) 
	    {
	        Thread t = new Thread(group, r,
	                              namePrefix + threadNumber.getAndIncrement(),
	                              0);
	        t.setDaemon(true);	// THIS IS IMPORTANT !!
	        
	        if (t.getPriority() != Thread.NORM_PRIORITY)
	            t.setPriority(Thread.NORM_PRIORITY);
	        
	        return t;
	    }
	}
}


